package com.nextbus.main;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.maps.MapView;
import com.nextbus.transit.TransitSystem;
import com.nextbus.ui.BusOverlay;

/**
 * A Handler allows you to send and process Message and Runnable objects
 * associated with a thread's MessageQueue. Each Handler instance is associated
 * with a single thread and that thread's message queue. When you create a new
 * Handler, it is bound to the thread / message queue of the thread that is
 * creating it -- from that point on, it will deliver messages and runnables to
 * that message queue and execute them as they come out of the message queue.
 * 
 * There are two main uses for a Handler: (1) to schedule messages and runnables
 * to be executed as some point in the future; and (2) to enqueue an action to
 * be performed on a different thread than your own.
 * 
 * @author xxq
 * 
 */

public class UpdateHandler extends Handler {
    private final static String TAG = "UpdateHandler";

    // --------------------软件运行状态 --------------------------
    private String route;

    private int viewMode;

    private String direction;
    
    private boolean hasResumeLastRunState = false;

    // ---------------------Prefs 软件参数 --------------------------
    private boolean updateConstant;

    private boolean showUnpredictableBus;

    private boolean hideBlueCircle;

    private boolean showRoutePath;

    // ----------------------上次更新的时间 ---------------------------
    private long lastUpdateTime = -1;

    // ----------------------最小更新间隔时间 -------------------------
    private final static int UPDATE_DELAY = 15000;

    // ----------------------到云端抓取数据的操作类 -------------------
    UpdateAsyncTask updateHelper;

    private BusOverlay busOverlay;

    private BusOverlay stopOverlay;

    private MapView mapView;

    private ProgressBar pgsBar_updateStatus;

    public UpdateHandler() {

    }

    /**
     * cxd
     */
    private Context context;

    private ProgressDialog pgsDialog;

    private EditText editText_searchRoute;

    public UpdateHandler(Context context, MapView mapView,
            ProgressDialog pgsDialog, String route, int viewMode,
            boolean updateConstant, boolean showUnpredictableBus,
            boolean hideBlueCircle, boolean showRoutePath,
            BusOverlay busOverlay, Drawable busIcon, BusOverlay stopOverlay,
            Drawable stopIcon, String direction,
            ProgressBar pgsBar_updateStatus, EditText editText_searchRoute) {
        this.route = route;
        this.viewMode = viewMode;
        this.updateConstant = updateConstant;
        this.showUnpredictableBus = showUnpredictableBus;
        this.hideBlueCircle = hideBlueCircle;
        this.showRoutePath = showRoutePath;
        this.editText_searchRoute = editText_searchRoute;
        // -------------------------图层--------------------------
        this.mapView = mapView;
        this.busOverlay = busOverlay;
        this.stopOverlay = stopOverlay;

        // cxd
        this.context = context;
        this.pgsDialog = pgsDialog;
        this.direction = direction;

        this.pgsBar_updateStatus = pgsBar_updateStatus;
    }

    // 接受UpdateAsyncTask消息，处理UpdateAsyncTask消息
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        // 启动NextBus,会执行这个if，进行恢复操作，若持续更新，则sendEmptyMessageDelayed()进行循环调用
        if (msg.what == TransitSystem.OPERATION_TYPE_RESUME_LAST_RUN_STATE) {
            //初始化lastUpdateTime
            lastUpdateTime = TransitSystem.currentTimeMillis();
            // 将自动更新交由TransitSystem.OPERATION_TYPE_UPDATE_INSTANT来管
            sendEmptyMessage(TransitSystem.OPERATION_TYPE_UPDATE_INSTANT);
            hasResumeLastRunState = true;
            return;
        }

        if (msg.what == TransitSystem.OPERATION_TYPE_UPDATE_INSTANT) {
            // 自动更新
            if (updateConstant == true) {
                    sendEmptyMessageDelayed(TransitSystem.OPERATION_TYPE_UPDATE_INSTANT,
                            UPDATE_DELAY);
            }
            
            // 人为更新
            if (updateConstant == false && !hasResumeLastRunState) {
                if (TransitSystem.currentTimeMillis() - lastUpdateTime < UPDATE_DELAY) {
                    Toast.makeText(context, "请10秒之后更新", Toast.LENGTH_LONG).show();
                    return;
                }
            }
        }

        // 什么时候更新lastUpdateTime，当然在三种操作都会导致其改变
        if (msg.what == TransitSystem.OPERATION_TYPE_PRESS_BUS || 
                msg.what == TransitSystem.OPERATION_TYPE_PRESS_STOP) {
            lastUpdateTime = TransitSystem.currentTimeMillis();
        }
        
        pgsBar_updateStatus.setVisibility(View.VISIBLE);
        if (updateHelper != null) {
            updateHelper = null;
        }
        updateHelper = new UpdateAsyncTask(context, mapView, pgsDialog,
                busOverlay, stopOverlay, route, direction,
                pgsBar_updateStatus, editText_searchRoute);
        updateHelper.triggerUpdate(msg.what, route, viewMode);
    }

    public String getRoute() {
        return route;
    }

    public void setRoute(String route) {
        this.route = route;
    }

    public int getViewMode() {
        return viewMode;
    }

    public void setViewMode(int viewMode) {
        this.viewMode = viewMode;
    }

    public boolean isUpdateConstant() {
        return updateConstant;
    }

    public void setUpdateConstant(boolean updateConstant) {
        this.updateConstant = updateConstant;
    }

    public boolean isShowUnpredictableBus() {
        return showUnpredictableBus;
    }

    public void setShowUnpredictableBus(boolean showUnpredictableBus) {
        this.showUnpredictableBus = showUnpredictableBus;
    }

    public boolean isHideBlueCircle() {
        return hideBlueCircle;
    }

    public void setHideBlueCircle(boolean hideBlueCircle) {
        this.hideBlueCircle = hideBlueCircle;
    }

    public boolean isShowRoutePath() {
        return showRoutePath;
    }

    public void setShowRoutePath(boolean showRoutePath) {
        this.showRoutePath = showRoutePath;
    }

    public long getLastUpdateTime() {
        return lastUpdateTime;
    }

    public void setLastUpdateTime(long lastUpdateTime) {
        this.lastUpdateTime = lastUpdateTime;
    }

    public UpdateAsyncTask getUpdateHelper() {
        return updateHelper;
    }

    public void setUpdateHelper(UpdateAsyncTask updateHelper) {
        this.updateHelper = updateHelper;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

}
